#pragma once
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
#include <cmath>
#include "Comm.hpp"
#include "Vector.hpp"


class Collision
{
public:
	Collision() = default;
	~Collision() = default;

	static bool IsOverLapping(const std::pair<double, double>& range1, const std::pair<double, double>& range2)
	{
		return !(range1.second < range2.first || range2.second < range1.first);
	}

	// 在提供凸多边形的点时，需要按逆时针方向进行提供
	static bool CheckCollision(const std::vector<Point>& figure1, const std::vector<Point>& figure2)
	{
		// 算出两个凸多边形的各个边的法向量
		std::vector<Vector> normal_vector;
		for (int i = 1; i < figure1.size(); i++)
		{
			normal_vector.push_back(Vector( figure1[i]._x - figure1[i - 1]._x, figure1[i]._y - figure1[i - 1]._y ).GetNormalVector());
		}
		for (int i = 1; i < figure2.size(); i++)
		{
			normal_vector.push_back(Vector( figure2[i]._x - figure2[i - 1]._x, figure2[i]._y - figure2[i - 1]._y ).GetNormalVector());
		}

		//

		// 求出两个凸多边形在对应法向量产生的分离轴上的投影，并通过投影判断两者有没有发生重叠
		for (int i = 0; i < normal_vector.size(); i++) 
		{
			double figure1_min = INT_MAX, figure1_max = INT_MIN;
			for (int j = 0; j < figure1.size(); j++) 
			{
				double projection = Vector::DotProduct(normal_vector[i], Vector(figure1[j]._x, figure1[j]._y));
				figure1_min = std::min(figure1_min, projection);
				figure1_max = std::max(figure1_max, projection);
			}

			double figure2_min = INT_MAX, figure2_max = INT_MIN;
			for (int j = 0; j < figure2.size(); j++) {
				double projection = Vector::DotProduct(normal_vector[i], Vector(figure2[j]._x, figure2[j]._y));
				figure2_min = std::min(figure2_min, projection);
				figure2_max = std::max(figure2_max, projection);
			}

			if (!IsOverLapping({ figure1_min, figure1_max }, { figure2_min, figure2_max })) 
			{
				return false;
			}
		}

		return true;
	}
};